﻿angular.module("umbraco").controller("UE.DistrictController",
    function ($scope, districtResource) {
        $scope.province = "";
        $scope.city = "";
        $scope.district = "";

        districtResource.getProvince().then(function (response) {
            $scope.provinces = response;

            if ($scope.model.value != '' && $scope.model.value != undefined) {
                districtResource.getOne($scope.model.value).then(function (resOne) {
                    $scope.province = resOne.ProvinceCode;
                    districtResource.getCity($scope.province, $scope.model.config.threetier).then(function (resCity) {
                        $scope.citys = resCity;
                        $scope.city = resOne.CityCode;

                        if ($scope.model.config.threetier == 1) {
                            /**
                             之前数据是二级，又改为开启了三级，citycode为000000
                             使用区域数值重新赋值
                             */
                            if (resOne.CityCode == '000000') {
                                $scope.city = resOne.DistrictCode;
                            }
                            districtResource.getDistrict($scope.city).then(function (resDistrict) {
                                $scope.districts = resDistrict;
                                $scope.district = resOne.DistrictCode;
                            });
                        } else {
                            /**未开启三级*/
                            var citys = new Array("110100", "120100","500100","310100",);
                            if (citys.indexOf(resOne.CityCode) >= 0) {
                                $scope.city = resOne.DistrictCode;
                            }
                        }
                    });
                });
            }
        });

        $scope.changeProvince = function () {
            $scope.city = "";
            $scope.district = "";
            $scope.districts = "";
            $scope.model.value = "";
            districtResource.getCity($scope.province, $scope.model.config.threetier).then(function (response) {
                $scope.citys = response;
            });
        };

        $scope.changeCity = function () {
            $scope.district = "";
            if ($scope.model.config.threetier == 1) {
                $scope.model.value = "";
                districtResource.getDistrict($scope.city).then(function (response) {
                    $scope.districts = response;
                });
            } else {
                $scope.model.value = $scope.city;
            }
        };

        $scope.changeDistrict = function () {
            $scope.model.value = $scope.district;
        };
    }
);